package org.example.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.example.entity.RestBean;
import org.example.entity.vo.request.ConfirmResetVO;
import org.example.entity.vo.request.EmailRegisterVO;
import org.example.entity.vo.request.EmailResetVO;
import org.example.service.AccountService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.function.Function;
import java.util.function.Supplier;

@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {
    @Resource
    AccountService service;

    @GetMapping("/ask-code")
    public RestBean<Void> askVerifyCode(@RequestParam @Email String email, @RequestParam @Pattern(regexp = "(register|reset)") String type, HttpServletRequest request) {
        return massageHandler(() -> service.registerEmailVerifyCode(type, email, request.getRemoteAddr()));
    }

    @PostMapping("/register")
    @Transactional
    public RestBean<Void> register(@RequestBody @Valid EmailRegisterVO vo) {
        return massageHandler(() -> service.registerEmailAccount(vo));
    }

    @PostMapping("/reset-confirm")
    public RestBean<Void> resetConfirm(@RequestBody @Valid ConfirmResetVO vo) {
        return massageHandler(vo, service::resetConfirm);
    }

    @PostMapping("/reset-password")
    @Transactional
    public RestBean<Void> resetConfirm(@RequestBody @Valid EmailResetVO vo) {
        return massageHandler(vo, service::resetEmailAccountPassword);
    }
    private <T> RestBean<Void> massageHandler(T vo, Function<T, String> function) {
        return massageHandler(() -> function.apply(vo));
    }

    private RestBean<Void> massageHandler(Supplier<String> action) {
        String massage = action.get();
        return massage == null ? RestBean.success() : RestBean.failure(400, massage);
    }
}
